/**
 * Created by liuqingxia on 2016/3/28.
 */

var proxyTable;

var searchProxyTable;

var removeId;//要删除的代理节点的Id


/**
 * main入口
 */
$(document).ready(function () {

    proxyTable = $("#gddlProxy-table-container").ltsTable({
        url: getUrlBySuffix("/tddl/proxy/find"),
        templateId: 'gddlProxy-table-template'
    });

    searchProxyTable = $("#gddlProxy-table-container").ltsTable({
        url: getUrlBySuffix("/tddl/proxy/findByName"),
        templateId: 'gddlProxy-table-template'
    });

    LTS.colFormatter.optFormat = function (v, row) {
        return generateOptButtons();
    }

    LTS.colFormatter.emptyString = function (v, row) {
        return emptyString(v);
    }

    LTS.colFormatter.belongCluster = function (v, row) {
        return getClusterName(row);
    }

    LTS.colFormatter.statusFormat = function (v, row) {
        return proxyStatusSwitch(row);
    }

    proxyTable.post({pageSize: 10}, 1);

    clickSearchBtn();
    clickSearchAllBtn();
    clickProxyInsertBtn();

    clickRemoveBtn();
    clickConfirmRemoveBtn();
    clickUpdateBtn();
    clickConfirmUpdateBtn();

    clickRunState();

    clickStatusSwitchBtn();

});

/**
 * 点击查询按钮
 */
function clickSearchBtn() {
    $(document).on("click", "#searchBtn", function () {
        var name = $("#name").val();
        if (isNull(name)) {
            swal("警告", "请先输入代理节点名称", "warning");
            return;
        }
        var params = {name: $.trim(name)};
        searchProxyTable.post(params, 1);
    });
}

/**
 * 点击"全部"按钮
 */
function clickSearchAllBtn() {
    $(document).on("click", "#searchAllBtn", function () {
        proxyTable.post({pageSize: 10}, 1);
    });
}

/**
 * 点击"新建代理节点按钮"
 */
function clickProxyInsertBtn() {
    $(document).on("click", "#insertBtn", function () {
        window.location.href = getUrlBySuffix("/tddl/proxy/insert");
    });
}

/**
 * 点击"删除按钮"
 */
function clickRemoveBtn() {
    $(document).on("click", ".remove-btn", function (e) {
        removeId = getCurrentId($(this));
        //console.log("removeId=" + removeId);
        showRemoveTip(e, "remove-tip-modal");
    });
}

/**
 * 点击确认删除按钮
 */
function clickConfirmRemoveBtn() {
    $(document).on("click", "#confirm-remove-btn", function () {
        sendRemoveParamsToServer();
        $("#searchAllBtn").trigger("click");
    });
}

/**
 * 向后台发送删除请求
 */
function sendRemoveParamsToServer() {
    var params = {};
    params['id'] = removeId;
    try {
        $.postHttpSync(params, getUrlBySuffix("/tddl/proxy/remove"), function (json) {
            if (json && json.success) {
                $("#cancel-remove-btn").trigger("click");
                swal({
     				title : "操作成功",
     				text : json['message'],
     				type : "success"
     			}, function() {
     				var name = $("#name").val();
                   	proxyTable.post({pageSize: 10}, 1);
                	$("#remove-tip-modal").modal("hide");
     			});
                
            } else {
                $("#cancel-remove-btn").trigger("click");
                swal("失败", json.message, "error");
            }
        })
    } catch (e) {
        console.error("网络通信异常，请检查网络设置");
        swal("失败", "网络通信异常，请检查网络设置后，稍后重试", "error");
    }

    return;
}

/**
 * 点击编辑按钮
 */
function clickUpdateBtn() {
    $(document).on("click", ".update-btn", function () {
        $("#tddlProxy-edit-modal").modal("show");
        var currentId = getCurrentId($(this));
        var proxy = getObjectById(getUrlBySuffix("/tddl/proxy/findById"), currentId);
        fillEditForm(proxy);
    });
}

/**
 * 点击确认修改按钮
 */
function clickConfirmUpdateBtn() {
    $(document).on("click", "#proxyInsertCommit-btn", function () {
        var params = getFormParams("editForm");
        try {
            $.postHttp(params, getUrlBySuffix("/tddl/proxy/update"), function (json) {
                if (json && json.success) {
                    swal("成功", json['message'], "success");
                    $("#searchAllBtn").trigger("click");
                   
                    swal({
         				title : "操作成功",
         				text : json['message'],
         				type : "success"
         			}, function() {
         				 var name = $("#name").val();
                         if (name=="") {
                         	proxyTable.post({pageSize: 10},pageNum);
                         }else{
                         	var param = {name: $.trim(name)};
                             searchProxyTable.post(param, pageNum);
                         }
                    	$("#tddlProxy-edit-modal").modal("hide");
         			});
                } else {
                    swal("失败", json['message'], 'error');
                }
            })
        } catch (e) {
            console.error("通信异常，请检查网络配置后重试");
            swal("失败", "通信异常，请检查网络配置后重试", 'error');
        }
    });
}

/**
 * 点击状态按钮
 */
function clickRunState() {
    $(document).on("click", ".runState-btn", function () {
        var proxyId = getCurrentId($(this));
        //console.log(proxyId);
        window.location.href = getUrlBySuffix("/tddl/proxy/runStatus?proxyId=" + proxyId);
    });
}

/**
 * 点击"上线/下线"按钮
 */
function clickStatusSwitchBtn() {
    $(document).on("click", ".statusSwitch-btn", function () {

        var currentBtn = $(this);
        var id = getCurrentId($(this));
        var contentEle = $(this).parent().parent().find("span.status");
        var content = $.trim(contentEle.html());

        if ("可用" == content) {
            $.postHttp({proxyId: id}, getUrlBySuffix("/tddl/proxy/offline"), function (json) {
                if (json && json.success) {
                    swal("成功", json['message'], "success");
                    currentBtn.empty();
                    currentBtn.append('' +
                    '<span class="label label-primary" style="font-size: 14px">' +
                    '上线' +
                    '</span>');
                    contentEle.empty();
                    contentEle.append("不可用");
                } else {
                    swal("失败", json['message'], 'error');
                }
            });
        } else if ("不可用" == content) {
            $.postHttp({proxyId: id}, getUrlBySuffix("/tddl/proxy/online"), function (json) {
                if (json && json.success) {
                    swal("成功", json['message'], "success");
                    currentBtn.empty();
                    currentBtn.append('' +
                    '<span class="label label-primary" style="font-size: 14px">' +
                    '下线' +
                    '</span>');
                    contentEle.empty();
                    contentEle.append("可用");

                } else {
                    swal("失败", json['message'], 'error');
                }
            });
        }
    });


}


/**
 * 生成操作按钮
 * @returns {string}
 */
function generateOptButtons() {
    var optButtons = "" + updateBtn + removeBtn + "" +
        '<a href="javascript:;" class="runState-btn">' +
        '<span class="label label-success" style="font-size: 14px">' +
        '<i class="fa fa-eye"></i>&nbsp;&nbsp;' +
        '状态' +
        '</span>' +
        '</a>&nbsp;';
    return optButtons;
}

/**
 * 查找所属集群
 * @param row
 * @returns {string}
 */
function belongCluster(row) {
    var clusterId = row['clusterId'];
    return getClusterName(clusterId);
};

/**
 * 获取所属集群名称
 * @param row
 * @returns {*}
 */
function getClusterName(row) {
    var clusterName;
    var params = {};
    params['id'] = parseInt(row['clusterId']);
    $.postHttpSync(params, getUrlBySuffix("/tddl/cluster/findById"), function (json) {
        if (json && json.success) {
            var list = json['list'];
            var cluster = list[0];
            clusterName = cluster['name'];
        }
    })
    return clusterName;
}

/**
 * proxy状态
 * @param row
 * @returns {*}
 */
function proxyStatusSwitch(row) {
    if (0 == row.status) {
        return "<span class='status' style='color: green'>可用</span>" +
            "<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
            '<a href="javascript:;" class="statusSwitch-btn">' +
            '<span class="label label-primary" style="font-size: 14px">' +
            '下线' +
            '</span>' +
            '</a>&nbsp;';
    }
    return "<span class='status' style='color: red'>不可用</span>" +
        "<span>&nbsp;&nbsp;&nbsp;</span>" +
        '<a href="javascript:;" class="statusSwitch-btn">' +
        '<span class="label label-primary" style="font-size: 14px">' +
        '上线' +
        '</span>' +
        '</a>&nbsp;';
}